var btSerial = new (require('bluetooth-serial-port')).BluetoothSerialPort();
var iconv = require('iconv-lite');
var QRCode = require('qrcode')
const util = require('util');
var rp = require('request-promise');
var path = require("path");

function btWrite(buffer, callback) {
  btSerial.write(buffer, callback)
}

btWrite[util.promisify.custom] = (foo) => {
  return new Promise((resolve, reject) => {
    btWrite(foo, resolve, reject);
  });
};

const btWritePromise = util.promisify(btWrite);

function getText(str) {
  var buffer = iconv.encode(str, 'gbk');
  return buffer;
}

class Printer {

  constructor() {
  }

  start() {
    btSerial.on('found', function (address, name) {
      if (name !== 'Qsprinter') {
        return;
      }
      console.log(name);
      btSerial.findSerialPortChannel(address, function (channel) {
        btSerial.connect(address, channel, function () {
          console.log('connected');
          btSerial.on('data', function (buffer) {
            console.log(buffer.toString('utf-8'));
          });
        }, function () {
          console.log('cannot connect');
        });

        // close the connection when you're ready
        btSerial.close();
      }, function () {
        console.log('found nothing');
      });
    });
    btSerial.inquire();
  }

  write(qrcodeInfo, id, timeStr) {
    // generate qr code
    QRCode.toFile("./qrcode.jpg", qrcodeInfo, {
      width: 384,
      height: 384
    })
      .then(function () {
        var str = path.resolve("./qrcode.jpg");
        var qrcodePath = Buffer.from(str).toString('base64');
        str = path.resolve("./logo.jpg");
        var logoPath = Buffer.from(str).toString('base64');
        rp('http://localhost:8181/printerData?path=' + logoPath)
          .then((body) => btWritePromise(new Buffer(body, 'base64')))
          .then(() => btWritePromise(getText('识足鸟脚型分析报告\n')))
          .then(() => btWritePromise(getText('测量时间\n')))
          .then(() => btWritePromise(getText('报表ID\n')))
          .then(() => btWritePromise(getText('--------------------------\n')))
          .then(() => rp('http://localhost:8181/printerData?path=' + qrcodePath))
          .then((body) => btWritePromise(new Buffer(body, 'base64')))
          .then(() => btWritePromise(getText('查看报表：\n')))
          .then(() => btWritePromise(new Buffer([0x1b, 0x64, 0x02])))
          .then(() => console.log('finished'))
          .catch(function (err) {
            console.log(err)
          })
      })
      .catch(function (err) {
        console.log(err);
      });
    // let textBuffer = getText('mydata test');
    //       btSerial.write(textBuffer, function () {
    //         btSerial.write(new Buffer([0x1b, 0x64, 0x02]), function (err) {
    //           request('http://localhost:8181/printerData', function (error, response, body) {
    //             var originaldata = new Buffer(body, 'base64');
    //             btSerial.write(originaldata, function (err, bytesWritten) {
    //               if (err) console.log(err);
    //               btSerial.write(new Buffer([0x1d, 0x0c]), function () {
    //               });
    //             });
    //           })
    //         });
    //       })
  }

}

module.exports = Printer